﻿using System;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Windows.Threading;
using System.ServiceModel.Channels;
using System.ServiceModel;

namespace OnlineGameClient.Service
{
    public class ReceiveTimeoutNotifyBehavior : IEndpointBehavior, IClientMessageInspector
    {
        Action<int> _timeoutcallback;
        DispatcherTimer _timer;
        public ReceiveTimeoutNotifyBehavior(TimeSpan timeout, Action<int> timeoutcallback)
        {
            _timer = new DispatcherTimer();
            _timer.Interval = timeout;
            _timer.Tick += new EventHandler(_timer_Tick);
            _timer.Start();

            _timeoutcallback = timeoutcallback;
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            if (_timeoutcallback != null)
                _timeoutcallback(0);
        }

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(this);
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }


        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            _timer.Stop();
            _timer.Start();
            return null;
        }
    }
}
